<template>
  <view class="page-wrap">
	<scroll-view id="scrollview" @scrolltolower="videoPlayFalse" @scrolltoupper="videoPlayFalse" scroll-y="true" :scroll-top="scrollTop"  class="chat-container"       >
		 <view id="msglistview">
					  <!-- @longpress="deleteMsg(message)" -->
			 <view  v-for="(message,index) in messages" :id="'msg_'+index"   :key="'msg_'+index"  class="`message ${message.type}`">
								   
			   <view  v-if="message.type=='0'" :class="`user-message ${message.fromUserId==uid ? 'me' : 'other'}`">
					<image :lazy-load="true" class="avatar"  :src="message.fromUserId==uid ? user.avatarUrl : message.avatar" mode="aspectFit"></image>
					<view class="text">
						<view class="nickname">{{message.fromUserId==uid?"":message.fromUser}}</view>
						<view class="content" >
							<text @longpress="deleteMsg(message)" >{{message.msg}}</text>
						</view>
						<!-- <view class="read" v-if="message.fromUserId==uid">
							<text v-if="message.read=='1'">已读</text>
							<text class="not"  v-else>未读</text>
						</view> -->
					 </view>
					 
					 
			   </view>
			   <view   v-else-if="message.type=='2'||message.type==2" :class="`user-message ${message.fromUserId==uid ? 'me' : 'other'}`">
				<image :lazy-load="true" class="avatar"  :src="message.fromUserId==uid ? user.avatarUrl : message.avatar" mode="aspectFit"></image>
				<view class="text">
					<view class="nickname">{{message.fromUserId==uid?"":message.fromUser}}</view>
					<view >
						<image lazy-load="true" @longpress="deleteMsg(message)" @tap="viewImg(message)" style="max-width: 400rpx;" mode="widthFix" :src="message.picContent"></image>
					</view>
					<!-- <view class="read" v-if="message.fromUserId==uid">
						<text v-if="message.read=='1'">已读</text>
						<text class="not"  v-else>未读</text>
					</view> -->
				 </view>
			   </view>
								   
		   <view  v-else-if="message.type=='3'||message.type==3" :class="`user-message ${message.fromUserId==uid ? 'me' : 'other'}`">
				<image :lazy-load="true" class="avatar"  :src="message.fromUserId==uid ? user.avatarUrl : message.avatar" mode="aspectFit"></image>
				<view class="text">
					<view class="nickname">{{message.fromUserId==uid?"":message.fromUser}}</view>
					
					
					<view>
						<video
						   v-if="message.id==msgId"
						   controls
						   autoplay="true"
						   :id="message.id"
						   :src="videoUrl"
						   @fullscreenchange="screenChange"
						></video>
					
						<image v-if="message.id!=msgId" lazy-load="true" @longpress="deleteMsg(message)" @tap="videoShow(message)" style="max-width: 400rpx;" mode="widthFix" :src="message.picContent"></image>
					
					
					</view>
					
				 </view>
		   </view>
			<view v-if="message.type == '4'" class="system-message">{{message.msg}}</view>
		 </view> 
		</view> 
				    
  </scroll-view>
		    
		    <view class="input-panel" >
		           <input type="text" cursor-spacing='0' maxlength='-1' confirm-type='send' confirm-hold='false' bindconfirm='sendMessage' v-on:blur="unwrite"  v-on:focus="unwrite" v-bind:value="inputContent" @input="changeInputContent" class="send-input"/>
		           <view style="width:10%;" v-on:tap="emojiCheck"  class="send-emoji iconfont iconsmile" >😀</view>
		           <view style="width:10%;font-size: 80rpx;" v-on:tap="sendMoreCheck"  class="send-emoji iconfont iconsmile" >+</view>
		           <button v-if="inputContent.length>0" style="width:20%" @touchend.prevent="sendMessage" class="send-btn">发送</button> 
		    </view>
			<view v-if="sendEmoji" class="emoji_view">
			  <scroll-view class="emojis_scroll" scroll-x="false" scroll-y="true">
				<view class="emoji" v-for="(item,index) in emoji" :data-name="item" v-bind:key="index" v-on:tap="_emojiItem" >
					 <text>{{item}}</text>
				</view>
			  </scroll-view>
		   </view>
			 
			 <view v-if="sendMore" class="more_view" >
				<view class="more-item" @click="sendImage">
					<image style="width: 100rpx;height: 100rpx;" src="../../../../static/pic.png"></image>
					<text>图片</text>
				</view>
				<view class="more-item" @click="sendVideo">
					<image  style="width: 100rpx;height: 100rpx;" src="../../../../static/shipin.png"></image>
					<text>视频</text>
				</view>
				<view class="more-item" @click="showCustomMessageForm">
					<image style="width: 100rpx;height: 100rpx;" src="../../../../static/vediochat.png"></image>
					<text>视频通话</text>
				</view>
		</view>
 </view>
</template>

<script>
  
	import http from '../../../../common/request.js'
	import {openComDB,closeComDB,executeSQL,dbInit} from '../../../../common/sqlite.js'
	import data from '../../../../common/data.js'
	  var socket ;
	export default {
		onLoad:function(options) {
		    // this.scrollToBottom()
			this.id = options.id
			this.talkName = options.name;
			uni.setNavigationBarTitle({
				title:options.name
			})
			this.user = uni.getStorageSync('userKey');
			const uid=uni.getStorageSync('userKey').id;
			this.uid=uid;
			this.getChatList(options.id)
			//this.isOpenDB();
			//this.queryMsgFromSqlite(options.id);
			uni.onKeyboardHeightChange(res =>{
                     //获取键盘高度
                this.Keyboard=res.height;
				console.log('this.Keyboard',this.Keyboard);
				this.inputStyle = 'margin-bottom: '+res.height+'rpx';
			 })
			 this.socketLianjie();
		},
		onShow() {
			this.user = uni.getStorageSync('userKey');
			const uid=uni.getStorageSync('userKey').id;
			this.uid=uid;
			//this.socketLianjie()
		},
		onUnload() {
			console.log('---onUnload----')
			uni.closeSocket({
				  	reason:'退出登录',
					success:function(res){
						console.log('退出成功----',res);
					}
			})
		},
		onPageScroll() {
		},
		
		 mounted() {
		       
		    },
		    updated() {
		        this.scrollToBottom()
		    },
		data() {
			return {
				msgId:'',
				videoUrl:'',
				videoContext :{},
				 danmuList: [],
				            danmuValue: '',
							Keyboard:0,
							inputStyle:'margin-bottom: 0rpx;',
				     scrollTop: 0,
				     id:"",
					 uid:"",
					 talkName:"",
				     registerMsg:[],
				     profession:"",
				     messages: [],         // 聊天记录
				     msg: '',              // 当前输入
				     user:{},
					 childrenId: 'msg_-1',            // �后�条消息的ID
				     inputContent: '',
				      emoji:[
				        '😀','😁','😂','😃','😄','😅','😆','😉','😇','😐','😑','😶','😏','😣','😥','😮','😯',
				        '😊','😋','😎','😍','😘','😗','😙','😚','😨','😬','😰','😱','😳','😵','😡','😠','😧',
				        '😪','😫','😴','😌','😛','😜','😝','😒','😓','😔','😕','😲','😷','😖','😞','😟','😤','😢','😭','😦'],
				      sendEmoji:false,
				      sendMore:false
			}
		},
		methods: {
			  videoErrorCallback: function(e) {
			            uni.showModal({
			                content: e.target.errMsg,
			                showCancel: false
			            })
			        },
					videoPlayFalse(){
						this.msgId = '';
					},
			socketLianjie(){
				// console.log(uni.getStorageSync('userKey'))
			   socket = uni.connectSocket({
			        url: data.websocket+uni.getStorageSync('userKey').id,
				  
			       header:{
			         'content-type': 'application/json'
			       },
				   success: (result) => {
				   	 // console.log('socketLianjie成功--obj'+JSON.stringify(result))
				   }
			     })
				 // socket.onOpen((result) => {
					//     this.getChatList(this.id)
				 // })
				 // socket.onError((result) => {
					//     this.getChatList(this.id)
				 // })
				 // socket.onClose((result) => {
					//     this.getChatList(this.id)
				 // })
				 socket.onMessage((result) => {
					 //this.insertMsgToSqlite(result);
					    this.getChatList(this.id)
				 })
				 // uni.onSocketMessage((result)=>{
					//  this.getChatList(this.id)
				 // })
				 uni.onSocketClose(function(result){
					 console.log('-----onSocketClose',result)
				 })
			  },
			 
			 screenChange(e) {
			   let fullScreen = e.detail.fullScreen; // 值true为进入全屏，false为退出全屏
			   console.log(e, "全屏");
			   if (!fullScreen) {
			     //退出全屏
			     this.msgId = '';   // 隐藏播放盒子
			   }
			 },
			 // 触发全屏播放的点击事件
			 videoShow(item) {
				 console.log(item);
				  this.videoUrl = item.picOri;
				this.msgId = item.id;  // 显示播放
			 },
			 
			  changeInputContent(e) {
			      this.inputContent=e.detail.value
				  console.log('changeInputContent----')
			  },
			    emojiCheck(){
			      if(this.sendEmoji){
			          this.sendEmoji=false
			      }else{
			         this.sendEmoji=true
					  this.sendMore = false
			      }
			    },
				
				sendMoreCheck(){
				  if(this.sendMore){
				      this.sendMore=false
				  }else{
				     this.sendMore=true
					 this.sendEmoji=false
				  }
				},
				unwrite(){
				   this.sendEmoji=false;
				   this.sendMore=false;
				  this.scrollTop=100000;
				  this.scrollToBottom()
				},
				  _emojiItem(e){
				     let msg= e.currentTarget.dataset.name;
					 this.inputContent = this.inputContent+msg
				 },
				 viewImg(message){
					 console.log('134---------1234');
					this.getMessage(message);
				 },
				 
				 
				 async getMessage(message) {
					    console.log(12345);
				 		const res = await http.request({
				 			url: '/message/image/'+message.id,
				 			method:'GET'
				 		})
						if(res.data.code==0){
							  let imgs=res.data.data.images
							  console.log(res.data.data.images[res.data.data.index]);
							 uni.previewImage({
							 	 current:res.data.data.index,
							 	 urls:imgs
							 })
						}
				 	
				 },
				 
				 
				 viewVideo(message){
					 
				 },
				 
				 queryImageListFromSqlite(toUserId){
				    let user=uni.getStorageSync('userKey')
				    var querySql = 'select id,picOri from message WHERE  (  ( fromUserId = '+user.id+' AND toUserId = '+toUserId+' ) OR ( fromUserId = '+toUserId+' AND toUserId = '+user.id+'  )  ) ';
				    executeSQL('ppchatmsg',querySql , res => {
				 			 this.checkNum(res);
				 		 this.messages = res;
				     })
				 	this.scrollToBottom();
				 },
				 
				 
				 
				 queryMsgFromSqlite(toUserId){
				    let user=uni.getStorageSync('userKey')
				    var querySql = 'select * from message WHERE  (  ( fromUserId = '+user.id+' AND toUserId = '+toUserId+' ) OR ( fromUserId = '+toUserId+' AND toUserId = '+user.id+'  )  ) ';
				    executeSQL('ppchatmsg',querySql , res => {
				 			 this.checkNum(res);
				 		 this.messages = res;
				     })
				 	this.scrollToBottom();
				 },
				
				 deleteMsg(message){
					 uni.showModal({
					                 title: '确定要删除信息吗?',
					                 content: '',
					                 success: (result) => {
										 if(result.confirm){
											 this.delete(message.id)
										 }
					                 	
					                 }
					             });
				 },
				 async sendMessage() {
					    const msg = {};
					    msg.toUserId = this.id
					    msg.fromUserId = uni.getStorageSync('userKey').id;
					    msg.type = 0;
					    msg.messages = this.inputContent;
				 		const res = await http.request({
				 			url: '/message/add',
				 			method:'POST',
				 			data:JSON.stringify(msg)
				 		})
						 this.getChatList(this.id)
					this.inputContent=''
				 },
				async delete(id) {
				 		const res = await http.request({
				 			url: '/message/remove?id='+id,
				 			method:'POST'
				 		})
						this.deleteMsgFromSqlite(id);
				 	this.getChatList(this.id)
					//  this.queryMsgFromSqlite(this.id);
				 },
				 
				 async getChatList(id) {
					     const msg = {};
					     msg.toUserId = id
					     const uid=uni.getStorageSync('userKey').id
					   
					     if(undefined == uid || null == uid || '' == uid){
					       return false;
					     }
						 msg.fromUserId = uid;
				 		const res = await http.request({
				 			url: '/message/list_talk',
				 			method:'POST',
				 			data:JSON.stringify(msg)
				 		})
						 this.checkNum(res.data.data)
						if(res.data.code==0){
							 this.messages = res.data.data
						}
				 	
				 },
				 insertMsgToSqlite(msg){
                    var msgObj = JSON.parse(msg.data);
					if(undefined==msgObj.picContent){
                           msgObj.picContent ='';
					}
					
					if(msgObj.insert == '1'){
						var sql = "INSERT INTO message (id, msg, avatar,photoUrl,username, type, status, sendTime, fromUserId, toUserId, fromUser, toUser,picContent,picOri,isMe,read) VALUES (";
											sql+=" '"+msgObj.id+"',";
											sql+=" '"+msgObj.msg+"',";
											sql+=" '"+msgObj.avatar+"',";
											sql+=" '"+msgObj.photoUrl+"',";
											sql+=" '"+msgObj.username+"',";
											sql+=" '"+msgObj.type+"',";
											sql+=" '"+msgObj.status+"',";
											sql+=" '"+msgObj.sendTime+"',";
											sql+=" '"+msgObj.fromUserId+"',";
											sql+=" '"+msgObj.toUserId+"',";
											sql+=" '"+msgObj.fromUser+"',";
											sql+=" '"+msgObj.toUser+"',";
											sql+=" '"+msgObj.picContent+"',";
											sql+=" '"+msgObj.picOri+"',";
											sql+=" '"+msgObj.isMe+"',";
											sql+=" '"+msgObj.read+"'";
						sql+=' ) ';
						executeSQL('ppchatmsg', sql, res => {})
						  this.queryMsgFromSqlite(this.id);
					}else{
						var sql = " UPDATE message SET read = '1' WHERE id =  '"+msgObj.id+"' ";
						executeSQL('ppchatmsg', sql, res => {})
						  this.queryMsgFromSqlite(this.id);
					}

				    
				  },


            openDB: function() {
                //SQLite     
                openComDB('ppchatmsg', '_doc/ppchatmsg.db', res => {
                    dbInit();
                });
            },

             isOpenDB: function() {
                var isOpen = plus.sqlite.isOpenDatabase({
                    name: 'ppchatmsg', //数据库的名字 
                    path: '_doc/ppchatmsg.db' //地址 
                });
                // console.log(' console.log(!isOpen);',!isOpen);
 
                 this.openDB(); //
            },

  
				

				 deleteMsgFromSqlite(id){
                    executeSQL('ppchatmsg', 'delete from message where id ="'+id+'"', res => {
						  this.messages = res;
                    })
				},
				 
				 checkNum(list){
					 this.childrenId='msg_'+(list.length-1);
				 },
			
				 
				  // 滚动至聊天底��
				         scrollToBottom(t) {
				             let that = this
				             let query = uni.createSelectorQuery()
				             query.select('#scrollview').boundingClientRect()
				             query.select('#msglistview').boundingClientRect()
				             query.exec((res) => {
				                 if(res[1].height > res[0].height){
				                     that.scrollTop = res[1].height
				                 }else{
									 that.scrollTop =  res[0].height;
								 }
				             })
				         },
						 
						 
			sendImage() {
				uni.chooseImage({
					count :4,
					success :(res) => {
						uni.uploadFile({
						            url: data.api+'/message/add_pic?toUserId='+this.id, 
						            filePath: res.tempFilePaths[0],
						            name: 'file',
									header:{authorization:uni.getStorageSync('authorization')},
						            success: (uploadFileRes) => {
										console.log(uploadFileRes.data)
						            },
						        });
					}
				});
			},	 
						 
						 
						 
						 
				sendVideo() {
					uni.chooseVideo({
						sourceType: ['camera', 'album'],
						success :(res) => {
							uni.uploadFile({
							            url: data.api+'/message/add_video?toUserId='+this.id, 
							            filePath: res.tempFilePath,
							            name: 'file',
										header:{authorization:uni.getStorageSync('authorization')},
							            success: (uploadFileRes) => {
											console.log(uploadFileRes.data)
											this.userinfo = JSON.parse(uploadFileRes.data)
											uni.setStorageSync('userKey',this.userinfo)
							            },
							        });
						}
					})
				},			 
			 
				 
		}
	}
</script>

<style>

.page-wrap {
  display: flex;
  flex-direction: column;
  background: #ebebeb;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
}
.chat-container {
  flex: 1;
  text-align: center;
  overflow-y:auto;
}
.system-message {
  font-size: 14px;
  line-height: 14px;
  color: #fff;
  background: #cecece;
  border-radius: 4px;
  display: inline-block;
  padding: 8rpx 15rpx;
  margin: 30rpx 0 10rpx;

}
.user-message {
  margin: 38rpx 20rpx 0 20rpx;
  text-align: left;
  font-size: 0;
  display: flex
}
.user-message.me {
  flex-direction: row-reverse;
  margin-bottom: 20rpx;
}
.avatar {
  width: 84rpx;
  height: 84rpx;
  border-radius: 10%;
}
.text {
  display: inline-block;
  vertical-align: top;
}
.user-message.other .text {
  margin-left: 19rpx;
}
.user-message.me .text {
  margin-right: 19rpx;
}
.text .nickname {
  color: #737373;
  font-size: 14px;
  margin-bottom: 6rpx;
}

.text .read {
  float: right;
  color: #737373;
  font-size: 12px;
  margin-top: 6rpx;
}
.text .read .not{
	 color: #1E90FF;
}
.text .content {
  border: #ccc 1rpx solid;
  border-radius: 30rpx;
  background: #fff;
  font-size: 36rpx;
  line-height: 36rpx;
  padding: 20rpx;
  position: relative;
}
.user-message.me .text .content {
  background: #a0e75b;
  border-radius: 10%;
  max-width: 180px;
  word-wrap: break-word;
}
.text .content::after,.text .content::before {
  font-size: 0;
  position: absolute;
  width: 0;
  height: 0;
  content: '';
  border: 13rpx dashed transparent;
}

.user-message.other .text .content::after,.user-message.other .text .content::before {
  right: 100%;
  border-right-style: solid;
}
.user-message.other .text .content::before {
  top: 18rpx;
  border-right-color: #ccc;
}
.user-message.other .text .content::after {
  border: 12rpx solid transparent;
  top: 19rpx;
  border-right-color: #fff;
}

.user-message.me .text .content::after,.user-message.me .text .content::before {
  left: 100%;
  border-left-style: solid;
}

.user-message.me .text .content::before {
  top: 18rpx;
  border-left-color: #70b44d;
}
.user-message.me .text .content::after {
  border: 12rpx solid transparent;
  top: 19rpx;
  border-left-color: #a0e75b;
}
.text .content.img {
  border: #ccc 1rpx solid;
  border-radius: 4px;
  background: #fff;
  font-size: 30rpx;
  line-height: normal;
  padding: 10rpx;
  position: relative;
  text-align: center;
  max-width: 560rpx;
}
.text .content.img image {
  max-width: 100%;
}

.input-panel {
  height: 100rpx;
  box-sizing: border-box;
  padding: 13rpx 20rpx 0;
  background: #f5f5f7;
  border-top:#d7d7d9 1rpx solid;
  box-sizing: border-box;
  display: flex;
}
.pic-icon {
  width: 60rpx;
  height: 44rpx;
  margin: 15rpx 20rpx 0 0;
  background:url(http://imgcache.qq.com/open_proj/proj_qcloud_v2/wechat_mc/pic/send.svg);
  display: none;
}
.send-input {
  flex: 1;
  height: 72rpx;
  background: #fff;
  border:#ddd 1rpx solid;
  border-radius: 3px;
  margin-right: 20rpx;
  box-sizing: border-box;
  padding: 0 10rpx;
}
.send-btn {
  text-align: center;
  height: 72rpx;
  background-color: #a0e75a;
  font-size: 28rpx;
}

.send-emoji {
  height: 72rpx;
  font-size: x-large;
  display: flex;
  align-items: center;
  justify-content: center;
}

.me .nickname {
  display: none;
}


.emojis_scroll{
  display: block;
  float: left;
  width: 100%;
  height: 400rpx;
  padding-left: 25rpx;
}

.emoji{
  display: block;
  float: left;
  width: 100rpx;
  height: 100rpx;
  font-size: 70rpx;
  text-align: center;
}



.emoji_view{
  box-sizing: border-box;
  padding: 13rpx 20rpx 0;
  background: #f5f5f7;
  border-top:#d7d7d9 1rpx solid;
  box-sizing: border-box;
  display: flex;
}

.hello_first{
  position:relative;
  display:block;
  margin-left:auto;
  margin-right:auto;
  padding-left:14rpx;
  padding-right:14rpx;
  padding-bottom: 25rpx;
  box-sizing:border-box;
  font-size:medium;
  text-align:center;
  text-decoration:none;
  line-height:2.55555556;
  border-radius:50rpx;
  -webkit-tap-highlight-color:transparent;
  overflow:hidden;
  color:red;
  width: 50%;
  height: 50%;
  margin-bottom: 50rpx;
  background-color:#F8F8F8;

}

.more-item{
	display: flex;
			flex-direction: column;
			width: 150rpx;
			height: 150rpx;
			margin-right: 20rpx;
			align-items: center;
}
.more_view{
	height: 300rpx;
			width:100%;
			padding: 20rpx;
			box-sizing: border-box;
			display: flex;
}

.msgimg{  
    width: 500rpx;  
    height: 500rpx;  
	margin-bottom: 20rpx;
 /*   max-width: 500rpx;  
    max-height: 500rpx; */    
}  
@import url('../../../../static/iconfont.css');

</style>
